package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.system.CheckDao;
import jsyf.oa.dao.system.MessageDao;
import jsyf.oa.dao.system.MessageReceiverDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.system.MessageEntity;
import jsyf.oa.entity.system.MessageReceiverEntity;
import jsyf.oa.entity.system.MsgMainEntity;
import jsyf.oa.facade.system.MessageFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;

/**
 * Created by Maqiuqiu on 2018/7/21.
 */
@SuppressWarnings("all")
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class MessageService implements MessageFacade {
    @Value("${oa.URLConfig}")
    private String urlConfig;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private CheckDao checkDao;

    @Autowired
    private MessageReceiverDao messageReceiverDao;

    @Override
    public String save(String jsonData) {
        MsgMainEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), MsgMainEntity.class);
        Integer rows;
        if ("0".equals(entity.getMsgMain().getId()) || StringUtils.isBlank(entity.getMsgMain().getId())) {
            messageDao.add(entity.getMsgMain());
        } else {
            MessageEntity messageEntity = (MessageEntity) messageDao.getIBaseEntityById(entity.getMsgMain().getId());
            messageEntity.setCreateUserId(entity.getMsgMain().getCreateUserId());
            messageEntity.setCreateTime(entity.getMsgMain().getCreateTime());
            messageEntity.setContent(entity.getMsgMain().getContent());
            messageEntity.setDelFlag(entity.getMsgMain().getDelFlag());
            messageEntity.setOpenUrl(entity.getMsgMain().getOpenUrl());
            messageEntity.setOpenTitle(entity.getMsgMain().getOpenTitle());
            messageEntity.setMessageType(entity.getMsgMain().getMessageType());
            messageDao.update(messageEntity);
        }

        List<MessageReceiverEntity> messageModel = entity.getMessageReceiverList();
        if (messageModel != null && messageModel.size() > 0) {
            for (int i = 0; i < messageModel.size(); i++) {
                MessageReceiverEntity messageReceiver = messageModel.get(i);
                if (!StringUtils.isBlank(messageReceiver.getId())) {
                    messageReceiverDao.removeById(messageReceiver.getId());
                }
                messageReceiver.setMessageId(entity.getMsgMain().getId());
                messageReceiver.setUserId(messageReceiver.getUserId());
                messageReceiver.setUserType(messageReceiver.getUserType());
                messageReceiver.setReadFlag(messageReceiver.getReadFlag());
                messageReceiverDao.add(messageReceiver);
            }
        }
        return entity.getMsgMain().getId();
    }

    @Override
    public List<JSONObject> getMsgByUserId(String receiverUserId, String messageId) {
        StringBuffer condition = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<Object>();
        if (!StringUtils.isBlank(receiverUserId)) {
            condition.append(" AND receiverUserId = ? ");
            sqlArgs.add(receiverUserId);
        }
        if (!StringUtils.isBlank(messageId)) {
            condition.append(" AND id = ? ");
            sqlArgs.add(messageId);
        }
        condition.append(" AND receiverReadFlag = 0 ");
        condition.append(" AND messageType != 3 ");
        condition.append(" ORDER BY createTime DESC ");
        List<JSONObject> records = messageDao.getViewJSONListByPage(condition.toString(), sqlArgs.toArray(), 1, 5);
        return records;
    }

    @Override
    public Boolean setMessageReadFlag(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String receiverId = json.getString("receiverId");
        String readFlag = json.getString("flag");
        if (readFlag != null && readFlag.equals("1")) {
            MessageReceiverEntity messageReceiverEntity =
                    (MessageReceiverEntity) messageReceiverDao.getIBaseEntityById(receiverId);
            if (null != messageReceiverEntity) {
                messageReceiverEntity.setReadFlag(1);
                messageReceiverDao.update(messageReceiverEntity);
                return true;
            }
            return false;
        } else {
            return false;
        }

    }

    @Override
    public Boolean delById(String id) {
        return messageDao.delById(id) > 0;
    }

    @Override
    public JSONObject getMessageForApp(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = json.getString("userId");
        String dateTime = json.getString("dateTime");
        String readFlag = null;
        if (json.containsKey("readFlag")) {
            readFlag = json.getString("readFlag");
        }
        List<JSONObject> messageList = messageDao.getMessageForApp(userId, dateTime, readFlag);
        JSONObject result = new JSONObject();
        result.put("records", messageList);
        return result;
    }

    @Override
    public Boolean getMessageForSignIn() {
        String signDate = DateUtils.nowDayByString(messageDao.getCurrentTime());
        String dateTime = signDate + " 08:01:00";
        List<JSONObject> signList = messageDao.getMessageForSignIn(signDate, dateTime);
        if (signList!=null&&signList.size()>0){
            for (int i = 0; i < signList.size(); i++) {
                String managerId = signList.get(i).getString("managerId");
                //保存消息到消息表t_sys_message
                MessageEntity messageEntity = new MessageEntity();
                messageEntity.setCreateUserId(managerId);
                messageEntity.setCreateTime(messageDao.getCurrentTime());
                messageEntity.setContent("考勤签到");
                messageEntity.setMessageType(3);
                messageEntity.setDelFlag(0);
                messageEntity.setOpenUrl("/reportForm/errorMessage/quYuSignApp.html?&userId=" + managerId + "&dateTime=" + signDate);
                messageEntity.setOpenTitle(SIGN_REMIND_MESSAGE);
                messageDao.add(messageEntity);
                //保存第一审核人信息到消息收件人表t_sys_message_receiver
                MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                messageReceiverEntity.setMessageId(messageEntity.getId());
                messageReceiverEntity.setUserId(managerId);
                messageReceiverEntity.setUserType(0);
                messageReceiverEntity.setReadFlag(0);
                messageReceiverDao.add(messageReceiverEntity);
                //发送企业微信
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", managerId);
                msgObject.put("content", String.format(SIGN_REMIND_MESSAGE_WE,
                        urlConfig + messageEntity.getOpenUrl() + "&receiverId=" + messageReceiverEntity.getId()));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
            }
        }
        return true;
    }

    @Override
    public Boolean getMessageForDaQuSignIn() {
        String signDate = DateUtils.nowDayByString(messageDao.getCurrentTime());
        String dateTime = signDate + " 08:01:00";
        //查询大区经理
        List<JSONObject> managerList = messageDao.getMessageForUser(" AND main=1 AND roleName='大区经理' AND jobState!=1", new Object[]{});
        for (int i = 0; i < managerList.size(); i++) {
            String managerId = managerList.get(i).getString("id");
            String managerIds = "";
            //递归查询大区经理看到的数据
            String userIds = checkDao.getChilderByUserId(managerId, true);
            //剔除其他职位
            List<JSONObject> bigManagerList = messageDao.getMessageForUser(" AND id IN (" + userIds + ")" +
                    " AND roleName IN ('区域经理','区域组长','大区经理') AND jobState!=1", new Object[]{});
            for (int j = 0; j < bigManagerList.size(); j++) {
                managerIds += "'" + bigManagerList.get(j).getString("id") + "',";
            }
            if (managerIds.length() > 0) {
                managerIds = managerIds.substring(0, managerIds.length() - 1);
                //查询迟到和缺勤的人
                List<JSONObject> signList = messageDao.getMessageForDaQuSignIn(managerIds, signDate, dateTime);
                if (signList != null && signList.size() > 0) {
                    //保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(managerId);
                    messageEntity.setCreateTime(messageDao.getCurrentTime());
                    messageEntity.setContent("考勤签到");
                    messageEntity.setMessageType(3);
                    messageEntity.setDelFlag(0);
                    messageEntity.setOpenUrl("/reportForm/errorMessage/daQuSignApp.html?&userId=" + managerId + "&dateTime=" + signDate);
                    messageEntity.setOpenTitle(SIGN_REMIND_MESSAGE);
                    messageDao.add(messageEntity);
                    //保存第一审核人信息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(managerId);
                    messageReceiverEntity.setUserType(0);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);
                    //发送企业微信
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", managerId);
                    msgObject.put("content", String.format(SIGN_REMIND_MESSAGE_WE,
                            urlConfig + messageEntity.getOpenUrl() + "&receiverId=" + messageReceiverEntity.getId()));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                }
            }
        }
        return true;
    }

    @Override
    public Boolean getMessageForSupportSignIn() {
        String signDate = DateUtils.nowDayByString(messageDao.getCurrentTime());
        String dateTime = signDate + " 08:01:00";
        //查询区域总监/区域支持
        List<JSONObject> managerList = messageDao.getMessageForUser("  AND main=1 AND roleName IN ('区域总监','区域支持') AND jobState!=1", new Object[]{});
        for (int i = 0; i < managerList.size(); i++) {
            String managerId = managerList.get(i).getString("id");
            String managerIds = "";
            //递归查询大区经理看到的数据
            String userIds = checkDao.getChilderByUserId(managerId, true);
            //剔除其他职位
            List<JSONObject> bigManagerList = messageDao.getMessageForUser(" AND id IN (" + userIds + ")" +
                    " AND roleName IN ('区域经理','区域组长','大区经理','区域总监') AND jobState!=1", new Object[]{});
            for (int j = 0; j < bigManagerList.size(); j++) {
                managerIds += "'" + bigManagerList.get(j).getString("id") + "',";
            }
            if (managerIds.length() > 0) {
                managerIds = managerIds.substring(0, managerIds.length() - 1);
                List<JSONObject> signList = messageDao.getMessageForDaQuSignIn(managerIds, signDate, dateTime);
                //查询迟到和缺勤的人
                if (signList != null && signList.size() > 0) {
                    //保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(managerId);
                    messageEntity.setCreateTime(messageDao.getCurrentTime());
                    messageEntity.setContent("考勤签到");
                    messageEntity.setMessageType(3);
                    messageEntity.setDelFlag(0);
                    messageEntity.setOpenUrl("/reportForm/errorMessage/managerSignApp.html?&userId=" + managerId + "&dateTime=" + signDate);
                    messageEntity.setOpenTitle(SIGN_REMIND_MESSAGE);
                    messageDao.add(messageEntity);
                    //保存第一审核人信息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(managerId);
                    messageReceiverEntity.setUserType(0);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);
                    //发送企业微信
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", managerId);
                    msgObject.put("content", String.format(SIGN_REMIND_MESSAGE_WE,
                            urlConfig + messageEntity.getOpenUrl() + "&receiverId=" + messageReceiverEntity.getId()));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                }
            }
        }
        return true;
    }


}
